package com.sctvcloud.pingwu.ui.activities;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentManager;
import android.support.v4.util.ArrayMap;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.util.Pair;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.load.resource.gif.GifDrawable;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.github.chrisbanes.photoview.PhotoView;
import com.github.chrisbanes.photoview.PhotoViewAttacher;
import com.luck.picture.lib.PictureBaseActivity;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.permissions.RxPermissions;
import com.luck.picture.lib.tools.DebugUtil;
import com.luck.picture.lib.tools.PictureFileUtils;
import com.luck.picture.lib.widget.PreviewViewPager;
import com.ruihang.generalibrary.ui.widget.CustomFontTextView;
import com.ruihang.generalibrary.utils.IShares;
import com.ruihang.generalibrary.utils.ListUtils;
import com.sctvcloud.pingwu.R;
import com.sctvcloud.pingwu.application.Cache;
import com.sctvcloud.pingwu.application.Constances;
import com.sctvcloud.pingwu.beans.IntegralAddBean;
import com.sctvcloud.pingwu.beans.NewsInfoAdvertBean;
import com.sctvcloud.pingwu.http.AbsNetCallBack;
import com.sctvcloud.pingwu.http.NetUtils;
import com.sctvcloud.pingwu.ui.dialog.ShareAdvertImageFragment;
import com.sctvcloud.pingwu.ui.dialog.ShareFragment;
import com.sctvcloud.pingwu.ui.utils.GlideUtil;
import com.sctvcloud.pingwu.ui.utils.SkipUtil;
import com.sctvcloud.pingwu.utils.UserManager;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;


public class AdvertPicInfoActivity extends PictureBaseActivity implements View.OnClickListener {

    private ImageView return_iv;
    private CustomFontTextView share;
    private PreviewViewPager viewPager;
    private List<String> images = new ArrayList<>();
    private List<NewsInfoAdvertBean> adList = new ArrayList<>();
    private int position = 0;
    private String directory_path;
    private SimpleFragmentAdapter adapter;
    private LayoutInflater inflater;
    private RxPermissions rxPermissions;
    private loadDataThread loadDataThread;
    protected ShareAdvertImageFragment shareFragment;
    public static final String SHARE_TAG = "share_fragment";
    public static final String PIC_LIST = "pic_list";
    public static final String PIC_INFO_LIST = "pic_INFO_list";
    public static final String POS = "pos";
    private float downX;    //按下时 的X坐标
    private float downY;    //按下时 的Y坐标
    private int screenWidth;
    private int screenHeight;
    private ArrayList<Bitmap> bts = new ArrayList<Bitmap>();
    Bitmap bitmap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_advert_pic_info);
        WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        screenWidth = wm.getDefaultDisplay().getWidth();
        screenHeight = wm.getDefaultDisplay().getHeight();
        inflater = LayoutInflater.from(this);
        return_iv = (ImageView) findViewById(R.id.title_top_layout_back);
        share = (CustomFontTextView) findViewById(R.id.title_top_layout_edit);
        viewPager = (PreviewViewPager) findViewById(R.id.preview_pager);
        position = getIntent().getIntExtra(PictureConfig.EXTRA_POSITION, 0);
        directory_path = getIntent().getStringExtra(PictureConfig.DIRECTORY_PATH);

        images = (List<String>) getIntent().getSerializableExtra(PIC_LIST);
        adList = (List<NewsInfoAdvertBean>) getIntent().getSerializableExtra(PIC_INFO_LIST);

//        initBts();

        return_iv.setOnClickListener(this);
        share.setOnClickListener(this);
        initViewPageAdapterData();
        if (ListUtils.isListValued(adList)) {
            SkipUtil.skipToAddUserOperate(this, "" + this, 10, 9, "广告图片阅读", adList.get(0).getId(), Cache.getInstance().getCurrentChannelId());
        }
    }


    private void initViewPageAdapterData() {
        adapter = new SimpleFragmentAdapter();
        viewPager.setAdapter(adapter);
        viewPager.setCurrentItem(position);
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                String media = images.get(position);

            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
    }

    @Override
    public void onClick(View v) {
        if (v == return_iv) {
            finish();
            overridePendingTransition(0, com.luck.picture.lib.R.anim.a3);
        } else if (v == share) {
            if (ListUtils.isListValued(adList)) {
                showShareFragment(adList.get(0), new ShareFragment.OnShareFragmentClickListener() {
                    @Override
                    public void onClick(Pair<String, String> pair) {

                    }
                });
            }
        }
    }

    public class SimpleFragmentAdapter extends PagerAdapter {
        boolean isNormal = true;

        @Override
        public int getCount() {
            return images.size();
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            (container).removeView((View) object);
        }

        @Override
        public int getItemPosition(Object object) {
            // return super.getItemPosition(object);
            return POSITION_NONE;
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {

            View contentView = inflater.inflate(com.luck.picture.lib.R.layout.picture_image_preview, container, false);
            final PhotoView imageView = (PhotoView) contentView.findViewById(com.luck.picture.lib.R.id.preview_image);
            final ScrollView scroll = (ScrollView) contentView.findViewById(com.luck.picture.lib.R.id.scroll);
            final PhotoView normalImageView = (PhotoView) contentView.findViewById(com.luck.picture.lib.R.id.preview_image_normal);


            normalImageView.getAttacher().setOnClickItemListener(new PhotoViewAttacher.OnClickItemListener() {
                @Override
                public void clickResult() {
                    finish();
                    overridePendingTransition(0, com.luck.picture.lib.R.anim.a3);
                }
            });
            imageView.getAttacher().setOnClickItemListener(new PhotoViewAttacher.OnClickItemListener() {
                @Override
                public void clickResult() {
                    finish();
                    overridePendingTransition(0, com.luck.picture.lib.R.anim.a3);
                }
            });

            final String path = images.get(position);
            if (path != null) {

                boolean isHttp = PictureMimeType.isHttp(path);
                // 可以长按保存并且是网络图片显示一个对话框
                if (isHttp) {
                    showPleaseDialog();
                }
                if (PictureMimeType.isGifPic(path)) {
                    GlideUtil.getGlid(AdvertPicInfoActivity.this, path)
                            .asGif()
                            .error(R.drawable.icon_def_1_1)
                            .diskCacheStrategy(DiskCacheStrategy.SOURCE)
                            .listener(new RequestListener<String, GifDrawable>() {
                                @Override
                                public boolean onException(Exception e, String model, Target<GifDrawable> target, boolean isFirstResource) {
                                    dismissDialog();
                                    return false;
                                }

                                @Override
                                public boolean onResourceReady(GifDrawable resource, String model, Target<GifDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
                                    dismissDialog();
                                    return false;
                                }
                            })
                            .into(imageView);
                } else {

                    GlideUtil.getGlid(AdvertPicInfoActivity.this, path)
                            .listener(new RequestListener<String, GlideDrawable>() {
                                @Override
                                public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
                                    normalImageView.setVisibility(View.VISIBLE);
                                    scroll.setVisibility(View.GONE);
                                    GlideUtil.getGlid(AdvertPicInfoActivity.this, path)
                                            .fitCenter().error(R.drawable.icon_def_1_1)
                                            .into(normalImageView);
                                    return false;
                                }

                                @Override
                                public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
                                    if (resource.getIntrinsicHeight() / resource.getIntrinsicWidth() < 2) {
                                        isNormal = true;
                                    } else {
                                        isNormal = false;
                                    }
                                    if (isNormal) {
                                        normalImageView.setVisibility(View.VISIBLE);
                                        imageView.setVisibility(View.GONE);
                                        scroll.setVisibility(View.GONE);
                                        GlideUtil.getGlid(AdvertPicInfoActivity.this, path)
                                                .fitCenter().error(R.drawable.icon_def_1_1)
                                                .into(normalImageView);
                                    } else {
                                        normalImageView.setVisibility(View.GONE);
                                        imageView.setVisibility(View.VISIBLE);
                                        scroll.setVisibility(View.VISIBLE);
                                        GlideUtil.getGlid(AdvertPicInfoActivity.this, path)
                                                .error(R.drawable.icon_def_1_1)
                                                .into(imageView);
                                    }
                                    return false;
                                }
                            })
                            .into(imageView);


                }

                dismissDialog();


            }
            container.addView(contentView, 0);
            return contentView;
        }
    }

    private synchronized void showShareFragment(final IShares iShares, final ShareFragment.OnShareFragmentClickListener onShareFragmentClickListener) {
        shareFragment = new ShareAdvertImageFragment();
        shareFragment.setShares(iShares);
        shareFragment.setOnShareFragmentClickListener(onShareFragmentClickListener);

        shareFragment.setShareSuccessListener(new ShareAdvertImageFragment.ShareSuccess() {
            @Override
            public void OnShareSuccess(String shareType) {
                addInvitation(Constances.ADD_INTEGRAL_FORWARD, false);
                if (ListUtils.isListValued(adList)) {
                    SkipUtil.skipToAddUserOperate(AdvertPicInfoActivity.this, this + "", 14, 9, shareType + "--广告图片分享", adList.get(0).getId(), Cache.getInstance().getCurrentChannelId());
                }
            }
        });

        FragmentManager fm = getSupportFragmentManager();
        shareFragment.show(fm, SHARE_TAG);
        fm.executePendingTransactions();
    }
    /**
     * 获取网络图片
     *
     * @param imageurl 图片网络地址
     * @return Bitmap 返回位图
     */
    public Bitmap GetImageInputStream(String imageurl) {
        URL url;
        HttpURLConnection connection = null;
        Bitmap bitmap = null;
        try {
            url = new URL(imageurl);
            connection = (HttpURLConnection) url.openConnection();
            connection.setConnectTimeout(6000); //超时设置
            connection.setDoInput(true);
            connection.setUseCaches(false); //设置不使用缓存
            InputStream inputStream = connection.getInputStream();
            bitmap = BitmapFactory.decodeStream(inputStream);
            inputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    /**
     * 异步线程下载图片
     */
    class Task extends AsyncTask<String, Integer, Void> {

        protected Void doInBackground(String... params) {
            bitmap = GetImageInputStream((String) params[0]);
//            bts.add(bitmap);
            Log.e("- picture review- -", "Task add images path = " + params[0]);
            if (bts.size() == images.size()) {
                Message message = new Message();
                message.obj = bitmap;
                message.what = 0x123;
                handler.sendMessage(message);
            }
            return null;
        }

        protected void onPostExecute(Void result) {
            super.onPostExecute(result);

        }

    }


    // 进度条线程
    public class loadDataThread extends Thread {
        private String path;

        public loadDataThread(String path) {
            super();
            this.path = path;
        }

        public void run() {
            try {
                showLoadingImage(path);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }


    // 下载图片保存至手机
    public void showLoadingImage(String urlPath) {
        try {
            URL u = new URL(urlPath);
            String path = PictureFileUtils.createDir(AdvertPicInfoActivity.this,
                    System.currentTimeMillis() + ".png", PictureFileUtils.CAMERA_PIC_PATH);
            byte[] buffer = new byte[1024 * 8];
            int read;
            int ava = 0;
            long start = System.currentTimeMillis();
            BufferedInputStream bin;
            bin = new BufferedInputStream(u.openStream());
            BufferedOutputStream bout = new BufferedOutputStream(
                    new FileOutputStream(path));
            while ((read = bin.read(buffer)) > -1) {
                bout.write(buffer, 0, read);
                ava += read;
                long speed = ava / (System.currentTimeMillis() - start);
                DebugUtil.i("Download: " + ava + " byte(s)"
                        + "    avg speed: " + speed + "  (kb/s)");
            }
            bout.flush();
            bout.close();
            Message message = handler.obtainMessage();
            message.what = 200;
            message.obj = path;
            handler.sendMessage(message);
        } catch (IOException e) {
            dismissDialog();
            showToast(getString(com.luck.picture.lib.R.string.picture_save_error) + "\n" + e.getMessage());
            e.printStackTrace();
        }
    }


    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 200:
                    String path = (String) msg.obj;
                    showToast(getString(com.luck.picture.lib.R.string.picture_save_success) + "\n" + path);
                    dismissDialog();
                    break;
//                case 0x123:
//                    Bitmap b = (Bitmap) msg.obj;
//                    if (null != b) {
//                        bts.add(b);
//                    }
//                    Log.e("- picture review- -", "handler bts size = " + bts.size());
//                    if (null != bts && bts.size() == images.size()) {
//                        initViewPageAdapterData();
//                    }
//                    break;


            }
        }
    };

    @Override
    public void onBackPressed() {
        overridePendingTransition(0, com.luck.picture.lib.R.anim.a3);
        super.onBackPressed();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (loadDataThread != null) {
            handler.removeCallbacks(loadDataThread);
            loadDataThread = null;
        }

        if (null != bitmap && !bitmap.isRecycled()) {
            bitmap.recycle();
            bitmap = null;
        }

        for (int i = 0; i < bts.size(); i++) {
            if (null != bts.get(i) && !bts.get(i).isRecycled()) {
                bts.get(i).recycle();
                bts.set(i, null);
            }

        }

    }

//    private synchronized void showShareFragment(final IShares iShares, final ShareFragment.OnShareFragmentClickListener onShareFragmentClickListener) {
//        shareFragment = new ShareAdvertImageFragment();
//        shareFragment.setShares(iShares);
//        shareFragment.setOnShareFragmentClickListener(onShareFragmentClickListener);
//
//        shareFragment.setShareSuccessListener(new ShareAdvertImageFragment.ShareSuccess() {
//            @Override
//            public void OnShareSuccess(String shareType) {
//                addInvitation(Constances.ADD_INTEGRAL_FORWARD, false);
//                if (ListUtils.isListValued(adList)) {
//                    SkipUtil.skipToAddUserOperate(AdvertPicInfoActivity.this, this + "", 14, 9, shareType + "--广告图片分享", adList.get(0).getId(), Cache.getInstance().getCurrentChannelId());
//                }
//            }
//        });
//
//        FragmentManager fm = getSupportFragmentManager();
//        shareFragment.show(fm, SHARE_TAG);
//        fm.executePendingTransactions();
//    }

    /**
     * 增加积分
     * 1:签到;2:评论;3:转发;4:投稿;5:采用投稿;6:邀请码分享;7:新用户注册;8:输入邀请码
     *
     * @param type
     */
    protected void addInvitation(int type, final boolean isFinishView) {
        if (null != UserManager.getInstance().getUser()) {
            ArrayMap<String, Object> p = new ArrayMap<>();
            p.put("ruleType", type);
            p.put("userId", UserManager.getInstance().getUser().getPhoneNumber());
            p.put("token", UserManager.getInstance().getUser().getToken());
            NetUtils.getNetAdapter().postAddIntegral(this + "", p, new AbsNetCallBack<IntegralAddBean>(IntegralAddBean.class) {
                @Override
                public void onSuc(IntegralAddBean result) {
                    String addMsg = "";
                    switch (result.getRuleType()) {
                        case Constances.ADD_INTEGRAL_SIGN_IN:
                            addMsg = " 签到成功，奖励" + result.getIntegral() + "积分~";
                            break;
                        case Constances.ADD_INTEGRAL_COMMENT:
                            addMsg = " 评论成功，奖励" + result.getIntegral() + "积分~";
                            break;
                        case Constances.ADD_INTEGRAL_FORWARD:
                            addMsg = " 转发成功，奖励" + result.getIntegral() + "积分~";
                            break;

                        case Constances.ADD_INTEGRAL_USE_SUBMISSION:
                            addMsg = " 投稿被采用，奖励" + result.getIntegral() + "积分~";
                            break;
                        case Constances.ADD_INTEGRAL_SHARE_INVITATION:
                            addMsg = " 分享邀请码成功，奖励" + result.getIntegral() + "积分~";
                            break;
                        case Constances.ADD_INTEGRAL_REGISTER:
                            addMsg = " 注册成功，奖励" + result.getIntegral() + "积分~";
                            break;
                        case Constances.ADD_INTEGRAL_INPUT_INVITATION:
                            addMsg = " 提交邀请码成功，奖励" + result.getIntegral() + "积分~";
                            break;
                        case Constances.ADD_INTEGRAL_READ_NEWS:
                            addMsg = " 阅读新闻，奖励" + result.getIntegral() + "积分~";
                            break;
                        case Constances.ADD_INTEGRAL_DOUP:
                            addMsg = " 点赞成功，奖励" + result.getIntegral() + "积分~";
                            break;
                    }
                    if (!TextUtils.isEmpty(addMsg)) {
                        toastInCenter(addMsg);
                    }
                    if (isFinishView) {
                        finish();
                    }
                }

                @Override
                public void onEnd() {
                    super.onEnd();

                }

                @Override
                public void onError(Throwable ex, String errorMsg) {
                    super.onError(ex, errorMsg);
                }
            });
        }
    }

    public void toastInCenter(String str) {
        Toast toast = Toast.makeText(this, str, Toast.LENGTH_SHORT);
        View view = toast.getView();
        if (view != null) {
//            TextView tv = (TextView) view.findViewById(com.android.internal.R.id.message);
            TextView tv = (TextView) view.findViewById(Resources.getSystem().getIdentifier("message", "id", "android"));
            if (tv != null) {
                tv.setTextColor(Color.WHITE);
                tv.setTextSize(15);
            }
            view.setBackgroundResource(R.drawable.bg_corners_black_toast);
        }
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.show();
    }

    /**
     * 根据距离差判断 滑动方向
     *
     * @param dx X轴的距离差
     * @param dy Y轴的距离差
     * @return 滑动的方向
     */
    private boolean isSlideDown(float dx, float dy) {
        Log.e("Tag", "========X轴距离差：" + dx);
        Log.e("Tag", "========Y轴距离差：" + dy);
        if (Math.abs(dx) < Math.abs(dy)) {
            return dy > 0;
        } else {
            return false;
        }
    }

}